package com.fingard.xml;

import java.util.ArrayList;
import java.util.HashSet;

public class XmlOprHelper {

	/**合并xml，xml1为主，合并xml2的节点（xml1中没有的）*/
	public static String joinXml(String xml1, String xml2, String rootName) throws Exception{
		
		ArrayList<XElement> list1 = null;
		ArrayList<XElement> list2 = null;
		
		XmlTextReader reader1 = new XmlTextReader(xml1);
		if(reader1.read("/"+rootName)){
			list1 = reader1.readedXElement.getAllChildList();
		}
		
		XmlTextReader reader2 = new XmlTextReader(xml2);
		if(reader2.read("/"+rootName)){
			list2 = reader2.readedXElement.getAllChildList();
		}
		
		if(list1 != null && list2 != null){
			HashSet<String> hashName = new HashSet<String>();
			for(int i=0;i<list1.size();i++){
				String hKey = list1.get(i).name + "-"+ list1.get(i).getAttrValue("for");
				if(!hashName.contains(hKey)){
					hashName.add(hKey);
				}
			}
			for(int i=0;i<list2.size();i++){
				String key2 = list2.get(i).name + "-"+ list2.get(i).getAttrValue("for");
				if(!hashName.contains(key2)){
					list1.add(list2.get(i));
				}
			}
			XmlTextWriter writer = new XmlTextWriter();
			writer.writeStartElement(rootName);
			for(int i=0;i<list1.size();i++){
				writer.writeXElement(list1.get(i));
			}
			writer.writeEndDocument();
			return writer.toXmlString();
		}else if(list1 != null){
			return xml1;
		}else if(list2 != null){
			return xml2;
		}
		
		return "";
	}
}
